﻿using AnyCAD.Foundation;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Windows;

namespace PointCloudV;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void RenderControl_ViewerReady()
    {

    }

    Float32Buffer? ReadData(string fileName)
    {
        using (StreamReader reader = File.OpenText(fileName))
        {
            Float32Buffer mPositions = new Float32Buffer(0);
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                if (line == null)
                    continue;

                var items = line.Split(' ');
                if (items.Length < 3)
                    continue;

                for (int ii = 0; ii < 3; ++ii)
                {
                    mPositions.Append(float.Parse(items[ii]));
                }
            }
            return mPositions;
        }
    }

    string? GetFileName()
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();

        openFileDialog.DefaultExt = ".txt";
        openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

        Nullable<bool> result = openFileDialog.ShowDialog();

        if (result == true)
        {
            return openFileDialog.FileName;
        }
        return null;
    }

    private void OnLoadPointCloud(object sender, RoutedEventArgs e)
    {
        string? filePath = GetFileName();
        if (filePath == null)
            return;

        var positions = ReadData(filePath);
        if (positions != null)
        {
            PointCloud node = PointCloud.Create(positions, null, null, 1);
            node.SetColor(ColorTable.White);
            mRenderCtrl.ShowSceneNode(node);
        }
    }

    string OutputFile = "";
    string InputFile = "";
    void OnCreateBREP(object sender, RoutedEventArgs e)
    {
        var inputFile = GetFileName();
        if (inputFile == null)
            return;
        InputFile = inputFile;
        OutputFile = inputFile + ".igs";
        var exePath = PathUtil.GetProgramPath() + "runtimes\\win-x64\\native\\pcd2igs.exe";
        var processObject = new Process()
        {
            StartInfo = new ProcessStartInfo(exePath)
            {
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                CreateNoWindow = true,
                Arguments = $" --refinement 4 --iterations 5 --input \"{InputFile}\" --output \"{OutputFile}\"",
            }
        };
        processObject.EnableRaisingEvents = true;
        processObject.Exited += ProcessObject_Exited;
        try
        {
            processObject.Start();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void ProcessObject_Exited(object? sender, EventArgs e)
    {
        if (!System.IO.Path.Exists(OutputFile))
            return;

        var shape = ShapeIO.Open(OutputFile);
        mRenderCtrl.ShowShape(shape, ColorTable.LightGray);

        var positions = ReadData(InputFile);
        if (positions != null)
        {
            PointCloud node = PointCloud.Create(positions, null, null, 1);
            node.SetColor(ColorTable.White);
            mRenderCtrl.ShowSceneNode(node);
        }
    }
}